#include <kuai/sim/control.hpp>

namespace kuai {


	void ControlSet::start(SimulationEnvironment& env, EnergySet& eset) {
		if (env.getTID() == 0) {
			next_x.clear();	
			next_x.resize(funcs.size(), 0);
		}
		for (std::vector<SimulationControl*>::const_iterator 
			it = funcs.begin(); it != funcs.end(); ++it)
		{
			(*it)->start(env, eset);
			env.wait();
		}
	}

	void ControlSet::finish(SimulationEnvironment& env, EnergySet& eset, size_t nstep) {
		for (std::vector<SimulationControl*>::const_iterator 
			it = funcs.begin(); it != funcs.end(); ++it)
		{
			(*it)->finish(env, eset, nstep);
			env.wait();
		}
	}
		
	void ControlSet::finalize(SimulationEnvironment& env, EnergySet& eset) {
		for (std::vector<SimulationControl*>::const_iterator 
			it = funcs.begin(); it != funcs.end(); ++it)
		{
			(*it)->finalize(env, eset);
		}
	}
		
	void ControlSet::act(SimulationEnvironment& env, EnergySet& eset, size_t istep) {
		for (size_t i = 0; i < funcs.size(); ++i) {
			if (next_x[i] < istep) {
				funcs[i]->act(env, eset, istep);
				env.wait();
				if (env.isMainThread()) {
					next_x[i] += funcs[i]->period;
				}
				env.wait();
			}
		}
	}


}
